package RequestHandler;

import DBControl.*;

public class WorkerPool {
    private static final int NUM_WORKER = 4;
    private Worker [] worker = new Worker[NUM_WORKER];
    
    public WorkerPool(SessionList sessionList, DBInterface dbi) {
        for (int i = 0; i < NUM_WORKER; i++) {
            worker[i] = new Worker(sessionList, dbi, i);
            worker[i].start();
        }
    }
    
    public Worker getAvailableWorker() {
        for (int i = 0; i < NUM_WORKER; i++) {
            if (worker[i].isIdle()) {
                worker[i].setOccupied();
                return worker[i];
            }
        }
        return null;
    }
    
    public void stop() {
        for (int i = 0; i < NUM_WORKER; i++) {
            worker[i].quit();
        }    
        for (int i = 0; i < NUM_WORKER; i++) {
            try {
                worker[i].join();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }   
    }
}